package edu.dublbo.app.generator.service;

import edu.dublbo.app.generator.entity.TBasicColumnType;
import edu.dublbo.app.generator.entity.TBasicModel;
import edu.dublbo.app.generator.entity.TBasicModelDetail;
import edu.dublbo.app.generator.entity.TBasicPropertyType;
import edu.dublbo.app.generator.mapper.TBasicModelDetailMapper;
import edu.dublbo.app.generator.mapper.TBasicModelMapper;
import edu.dublbo.app.generator.result.OptStatus;
import edu.dublbo.app.generator.result.Result;
import edu.dublbo.app.generator.util.Constant;
import edu.dublbo.app.generator.util.DemoUtils;
import edu.dublbo.app.generator.util.SnowflakeIdWorker;
import edu.dublbo.app.generator.util.StrUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.*;

/**
 * @author DubLBo
 * @since 2020-09-08 14:12
 * i believe i can i do
 */
@Service
public class BasicModelDetailService {
    private static final Logger logger = LoggerFactory.getLogger(BasicModelDetailService.class);
    @Resource
    private TBasicModelDetailMapper mapper;
    @Resource
    private TBasicModelMapper modelMapper;
    @Resource
    private SnowflakeIdWorker idWorker;

    public List<TBasicModelDetail> list(String id) {
        // 获取该模型下的模型明细列表
        Map<String, Object> condition = new HashMap<>();
        condition.put("modelId", id);
        condition.put("_order", "sort_no");
        return mapper.select(condition);
    }

    public List<TBasicPropertyType> listProTypes() {
        return mapper.getProTypeList();
    }

    public List<TBasicColumnType> listColTypes() {
        return mapper.getColTypeList();
    }

    public Result<Object> saveOrUpdate(TBasicModelDetail detail) {
        if (TBasicModelDetail.checkValid(detail)) {
            // 检查模型是否存在
            TBasicModel model = modelMapper.get(detail.getModelId());
            if (model != null) {
                // 判断是增加还是更新
                if (StrUtils.isBlank(detail.getId())) {
                    // add
                    // 判断属性名是否存在
                    Map<String, Object> con = new HashMap<>();
                    con.put("propertyName", detail.getPropertyName());
                    con.put("modelId",model.getId());

                    Integer num = mapper.selectCount(con);
                    if (num == null || num == 0) {
                        // 生成序号
                        con.clear();
                        con.put("modelId", model.getId());
                        List<TBasicModelDetail> details = mapper.select(con);
                        if (details == null || details.size() == 0) {
                            return Result.builder()
                                    .code(OptStatus.FAIL.code)
                                    .msg("系统尚未处理没有属性的模型，请返回重试")
                                    .build();
                        }
                        Set<Integer> sortNoSet = new HashSet<>();
                        for (TBasicModelDetail de : details) {
                            if (de.getSortNo() != null) {
                                sortNoSet.add(de.getSortNo());
                            }
                        }
                        List<Integer> sortNos = new ArrayList<>(sortNoSet);
                        int sortNo = DemoUtils.generateNextSortNo(sortNos);
                        logger.info("=========sortNooooo : " + sortNo);
                        Date curDate = new Date();
                        detail.setId(idWorker.nextStringId());
                        detail.setCreateUser(Constant.CURRENT_USER);
                        detail.setCreateTime(curDate);
                        detail.setModifyUser(Constant.CURRENT_USER);
                        detail.setModifyTime(curDate);
                        detail.setDeleteFlag(0);
                        detail.setInherentFlag(0);
                        detail.setSortNo(sortNo);
                        mapper.add(detail);
                    } else {
                        return Result.builder().code(OptStatus.FAIL.code).msg("属性名已存在").build();
                    }
                } else {
                    // update: 不允许修改 pro
                    detail.setModifyUser(Constant.CURRENT_USER);
                    detail.setModifyTime(new Date());
                    mapper.update(detail);
                }
            } else {
                return Result.builder()
                        .code(OptStatus.FAIL.code)
                        .msg("模型不存在，请刷新")
                        .build();
            }
        } else {
            return Result.builder()
                    .code(OptStatus.FAIL.code)
                    .msg("数据不合法，请修改后再提交")
                    .build();
        }

        return Result.builder()
                .code(OptStatus.SUCCESS.code)
                .build();
    }


    @Transactional
    public Result<Object> delete(String id) {
        // 判断该明细是否为固有的，即不可删除
        TBasicModelDetail modelDetail = mapper.get(id);
        if (modelDetail != null) {
            if (modelDetail.getInherentFlag() == 1) {
                return Result.builder()
                        .code(OptStatus.FAIL.code)
                        .msg("该属性为模型的固有属性，不可删除")
                        .build();
            } else {
                modelDetail.setModifyUser(Constant.CURRENT_USER);
                modelDetail.setModifyTime(new Date());
                modelDetail.setDeleteFlag(1);
                mapper.update(modelDetail);
            }
        }

        return Result.builder()
                .code(OptStatus.SUCCESS.code)
                .build();
    }
}
